<?php
/**
 * @title 50. Pow(x, n) - 二分迭代
 * @author start2004
 */

class Solution {

    /**
     * @param Float $x
     * @param Integer $n
     * @return Float
     */
    function myPow($x, $n) {
        /**
         * @since 2020-07-22 极端情况排除
         */
        if($n == 0){
            return 1;
        } else {}

        /**
         * @since 2020-07-22 求幂
         */
        if($n<0){
            $result = 1/self::find($x, 0-$n);
        } else {
            $result = self::find($x, $n);
        }

        /**
         * @return
         */
        return $result;
    }

    /**
     * @title 求幂
     * @author start2004
     * @since 2020-07-22 Created
     *
     * @param $x
     * @param $n
     */
    function find($x, $n){
        $pows = [
            1 => $x,
        ];

        /**
         * @since 2020-07-22 试出上限
         */
        $i = 1;
        $j = 2;
        while($j <= $n){
            $pows[$j] = $pows[$i] * $pows[$i];
            $i = $j;
            $j = $j<<1;
        }
        // return $pows;

        /**
         * @since 2020-07-22 求幂
         */
        $result = 1;
        while($n > 0){
            if($i>$n){
                $i = $i>>1;
                continue;
            } else {}
            $n -= $i;

            $result *= $pows[$i];
        }
        // return [$n, $result];

        /**
         * @return
         */
        return $result;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.22_4.php
 */
$datas = [
    [2.00000, 10],
    [2.10000, 3],
    [2.00000, -2],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->myPow($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
